<?php
class NewsController extends BaseController{
    public function __construct($action, $urlValues){
        if(!Helper::isLogin()){
            $_SESSION['lastUrl']=Helper::currentPageURL();
            header('Location: ' . BASE_URL . 'account/login'); 
        }
        parent::__construct($action, $urlValues);
        require("models/news.php");
        $this->model = new NewsModel();
    }
    
    protected function index(){
        $this->view->output($this->model->index());
    }
    
    protected function create(){
        if(!empty($_POST)){
            echo "<pre>";
            vardum ($_POST);
            echo"</pre>";
            exit();
            if(!isset($_POST['keyword']) || $_POST['keyword'] == "")
                $_POST['keyword'] = $_POST['title'];
            $result = $this->model->create($_POST);
            if($result){
                $alert = array(
                    'class' => 'alert-success',
                    'message' => 'Add new user success'
                );
                $_SESSION['message']=$alert;
                header('Location: ' . BASE_URL . 'news/index');
            }
        }
        $this->view->output($this->model->create(''));
    }
    
    protected function update(){
        if(!empty($_POST)){
            $news_id = $_POST['news_id'];
            foreach($_POST as $col=>$value){
                $data[$col] = $value;
            }   
            unset($data['news_id']);
            $result = $this->model->edit($news_id, $data);
            echo $result;
            if($result){
                $alert = array(
                    'class' => 'alert-success',
                    'message'=>'Update news successful'
                );
                $_SESSION['message'] = $alert;
                header('Location: ' . BASE_URL . 'News/index');
            }
        }
        $this->view->output($this->model->edit($news_id=$this->urlValues['id'],$data=''));
    }
    
    public function getlist(){
        $this->view->output($this->model->getList($this->urlValues['id'],"empty"));
    }
    
    protected function delete(){
        if(!empty($_POST)){
            $result = $this->model->delete('news', 'news_id IN(' . implode(',',$_POST['news_id']) .')');
        }else{
            $result = $this->model->delete('news', 'news_id=' . $this->urlValues['id']);
        }
        
        if($result){
            $alert = array(
                'class' => 'alert-success',
                'message' => 'Delete News success'
            );
            $_SESSION['message'] = $alert;
        }
        header('Location: ' . BASE_URL . 'News/index');
    }
}
?>